<template>
  <div>
    <bpmnTaskViewer v-if="isShow" :nodeCodes="nodeCodes" :activityList="nodeDatas" :xml="flowDef.source"/>
  </div>
</template>

<script>
import { getAction } from '@/services/manage'
import bpmnTaskViewer from '@/components/bpmn/bpmnTaskViewer'
import { mapMutations } from 'vuex'
import { ACCESS_TOKEN, ACCESS_REFRESH_TOKEN } from '@/store/mutation-types'
// import uni from './uni.webview.1.5.2'
export default {
  name: 'TaskPendingModal',
  components: { bpmnTaskViewer },
  mixins: [],
  props: {
    type: String // handling:办理 || claim:拾取 || history:审核历史
  },
  data() {
    return {
      url: {
        flowDef: '/camunda/process/details/',
        historics: '/camunda/task/historics/', // 审批流程数据
        active: '/camunda/task/active/'
      },
      formModel: { }, // 表单设计model
      formDef: {}, // 表单设计信息
      flowDef: {}, // 流程设计信息
      formData: {}, // 表单数据信息
      dynamicDataSatrt: {},
      processInstanceId: '',
      nodeCodes: {
        success: [],
        pending: [],
        error: []
      },
      nodeDatas: [],
      isShow: false,
      isInit: false,
      platform: ''
    }
  },
  methods: {
    ...mapMutations('account', ['setToken', 'setRefreshToken']),
    async getflowForm() { // 根据流程定义id获取绑定表单-发起单据及流程
      try {
        this.confirmLoading = true
        const res = await getAction(this.url.flowDef + this.processInstanceId)
        if (!res.success) {
          this.confirmLoading = false
          return this.$message.warning('未查询到发起表单')
        }
        const formModel = res.result.startFormModelDef && res.result.startFormModelDef.model && JSON.parse(res.result.startFormModelDef.model)

        // formModel.list = replaceFormModel(formModel.list)

        this.formModel = formModel
        this.flowDef = res.result
        this.formDef = res.result.formModelDef
        this.formData = res.result.startDatas

        this.confirmLoading = false
      } catch (error) {
        this.confirmLoading = false
      }
    },
    isJsonString(str) {
      try {
        const toObj = JSON.parse(str) // json字符串转对象
        /*
          判断条件
          1. 排除null可能性
          2. 确保数据是对象或数组
        */
        if (toObj && typeof toObj === 'object') {
          return true
        }
      } catch {
        // console.error('err')
        return false
      }
      return false
    },
    async getHistorics() { // 获取历史审批节点
      try {
        this.confirmLoading = true
        const res = await getAction(this.url.historics + this.processInstanceId)
        const res2 = await getAction(this.url.active + this.processInstanceId)
        this.confirmLoading = false
        this.nodeDatas = [].concat(res.result, res2.result)
        this.setFlowNodeStatus(res.result)
        this.setFlowNodePending(res2.result)
        console.log(this.nodeDatas)
        // this.type !== 'history' && this.setFlowNodePending(this.task)
      } catch (error) {
        this.confirmLoading = false
      }
    },
    setFlowNodeStatus(data) { // 获取已审批流程节点状态
      const completed = []
      const error = []
      data.forEach(item => {
        // 移除重复办理节点，以最后一次为准 -begin
        if (completed.includes(item.activityId)) {
          completed.splice(completed.indexOf(item.activityId), 1)
        }
        if (error.includes(item.activityId)) {
          error.splice(error.indexOf(item.activityId), 1)
        }
        // 移除重复，以最后一次为准 - end
        if (item.canceled) {
          error.push(item.activityId)
          // this.nodeDatas.push(item)
        } else {
          // this.nodeDatas.push(item)
          completed.push(item.activityId)
        }
      })
      this.$set(this.nodeCodes, 'completed', completed)
      this.$set(this.nodeCodes, 'error', error)
    },
    setFlowNodePending(data) { // 获取已审批流程节点状态
      const pending = []
      data.forEach(item => {
        // 移除重复办理节点，以最后一次为准 -begin
        if (this.nodeCodes.completed.includes(item.taskDefinitionKey)) {
          this.nodeCodes.completed.splice(this.nodeCodes.completed.indexOf(item.taskDefinitionKey), 1)
        }
        if (this.nodeCodes.error.includes(item.taskDefinitionKey)) {
          this.nodeCodes.error.splice(this.nodeCodes.error.indexOf(item.taskDefinitionKey), 1)
        }
        // 移除重复，以最后一次为准 - end
        pending.push(item.taskDefinitionKey)
      })
      this.$set(this.nodeCodes, 'pending', pending)
    },
    updateBpmnStatus(state) {
      this.$refs.kfbStart.updateBpmnStatus && this.$refs.kfbStart.updateBpmnStatus({ task: {
        processInstanceId: this.processInstanceId,
        id: this.id
      }, formData: this.formData, state })
    },
    async updateToken({ token, refreshToken }) {
      this.setToken(token)
      this.setRefreshToken(refreshToken)
      await this.getflowForm()
      await this.getHistorics()
      this.isShow = true
    }
  },
  async created() {
    const { processInstanceId, platform } = this.$route.query
    this.platform = platform
    // this.setToken(token)
    this.processInstanceId = processInstanceId
    window.updateBpmnStatus = (data) => {
      this.updateBpmnStatus(data.state)
    }

    window.updateToken = (data) => {
      this.updateToken(data)
    }
    const that = this
    if (platform === 'app') {
      document.addEventListener('UniAppJSBridgeReady', function() {
        window.uni.getEnv((res) => {
          console.log('当前环境：' + JSON.stringify(res))
          if (res.plus) {
            if (this.isInit) {
              return
            }
            this.isInit = true
            console.log(window.plus.storage.getItem('Access-Token'))
            that.updateToken({
              token: window.plus.storage.getItem(ACCESS_TOKEN),
              refreshToken: window.plus.storage.getItem(ACCESS_REFRESH_TOKEN)
            })
          }
        })
      })
    } else if (platform === 'web') { // H5
      window.addEventListener('message', function(event) {
        if (event.data.type === 'callFunction') {
          that[event.data.functionName](JSON.parse(event.data.data)) // 调用内部函数
        }
      })
    }
  },
  mounted() {
    if (this.platform === 'app') {
      setTimeout(() => {
        if (!this.isInit) {
          this.isInit = true
          this.updateToken({
            token: window.plus.storage.getItem(ACCESS_TOKEN),
            refreshToken: window.plus.storage.getItem(ACCESS_REFRESH_TOKEN)
          })
        }
      }, 3000)
    }
  }
}
</script>
